<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import useDialog from "@/hooks/useDialog";
import SysDialog from "@/components/SysDialog.vue";
import { ElMessage, type FormInstance } from "element-plus";
import SelectChecked from "@/components/SelectChecked.vue";
import { getDetailsApi } from "@/apis/role";
import {
  addApi,
  getListApi,
  getDetailApi,
  updateApi,
  deleteApi,
  resentPassWordApi,
} from "@/apis/user";
import type { UserListParm, UserModel } from "@/apis/user/UserModel";
import useInstance from "@/hooks/useInstance";
//获取全局实例
const { global } = useInstance();
const dialog = useDialog().dialog;
const addRef = ref<FormInstance>();
const selectRef = ref();
const roleIds = ref([]);
const searchPaparm = reactive<UserListParm>({
  currentPage: 1,
  pageSize: 2,
  phone: "",
  nickname: "",
  total: 0,
});
const addModel = reactive<UserModel>({
  id: "",
  username: "",
  password: "",
  email: "",
  gender: 1,
  phone: "",
  nickname: "",
  roleId: "",
});
const rules = {
  nickname: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { min: 11, max: 11, message: "长度为11个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
  ],
};
const handleSubmit = () => {
  searchPaparm.phone = searchPaparm.phone.trim();
  searchPaparm.nickname = searchPaparm.nickname.trim();
  searchPaparm.currentPage = 1;
  getList();
};
const handleReset = () => {
  searchPaparm.phone = "";
  searchPaparm.nickname = "";
  getList();
};
const tags = ref(1);
const handleAdd = () => {
  dialog.visible = true;
  dialog.title = "新增用户";
  options.value = [];
  tags.value = 1;
  getRoleDetails();
  nextTick(() => {
    selectRef.value.clear();
  });
  addRef.value?.resetFields();
};

const commit = () => {
  addRef.value?.validate(async (valid: any) => {
    let res = null;
    if (valid) {
      if (tags.value === 1) {
        res = await addApi(addModel);
      } else {
        console.log("update", addModel);
        res = await updateApi(addModel);
      }
    } else {
      console.log("error submit!!");
    }
    if (res && res.code == 200) {
      ElMessage.success(res.msg);
      dialog.visible = false;
      getList();
    }
  });
};
const options = ref<[]>([]);
const getRoleDetails = async () => {
  const res = await getDetailsApi();
  if (res && res.code == 200) {
    options.value = res.data;
  }
};
const selected = (value: Array<string | number>) => {
  addModel.roleId = value.join(",");
};
const tableList = ref([]);
const getList = async () => {
  let res = await getListApi(searchPaparm);
  if (res && res.code == 200) {
    tableList.value = res.data.records;
    searchPaparm.total = res.data.total;
  }
};
const handleSizeChange = (val: number) => {
  searchPaparm.pageSize = val;
  getList();
};
const handleCurrentChange = (val: number) => {
  searchPaparm.currentPage = val;
  getList();
};
const handleEdit = async (row: any) => {
  dialog.visible = true;
  dialog.title = "编辑用户";
  tags.value = 2;
  options.value = [];
  roleIds.value = [];
  await getRoleDetails();
  await getRoleList(row.id);
  nextTick(() => {
    Object.assign(addModel, row);
    addModel.gender = Number(row.gender);
    //selectRef.value.clear();
    //selectRef.value.selected(row.roleId.split(","));
  });
};
const handleDelete = async (id: string) => {
  const confim = await global.$myconfig("确认删除吗?");
  console.log(confim);
  if (confim) {
    let res = await deleteApi(id);
    if (res && res.code == 200) {
      ElMessage.success(res.msg);
      getList();
    } else {
      ElMessage.error(res.msg);
    }
  }
};

const getRoleList = async (userId: string) => {
  let res = await getDetailApi(userId);
  if (res && res.code == 200) {
    roleIds.value = res.data;
    addModel.roleId = res.data;
  }
};
onMounted(() => {
  getList();
});
const handlePassWord = async (row: any) => {
  const confim = await global.$myconfig("确认重置密码吗?");
  if (confim) {
    let res = await resentPassWordApi(row);
    if (res && res.code == 200) {
      ElMessage.success(res.msg);
      getList();
    }
  }
};
</script>

<template>
  <el-main>
    <el-form inline class="demo-form-inline" :model="searchPaparm">
      <el-form-item prop="nickname">
        <el-input
          v-model="searchPaparm.nickname"
          placeholder="请输入姓名"
        ></el-input>
      </el-form-item>
      <el-form-item prop="phone">
        <el-input
          v-model="searchPaparm.phone"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" icon="Search"
          >查询</el-button
        >
        <el-button @click="handleReset" icon="Close" type="warning"
          >重置</el-button
        >
        <el-button
          v-permission="[`sys:user:add`]"
          @click="handleAdd"
          icon="Plus"
          type="success"
          >新增</el-button
        >
      </el-form-item>
    </el-form>
    <SysDialog
      :title="dialog.title"
      :visible="dialog.visible"
      :width="dialog.width"
      :height="dialog.height"
      @onClose="dialog.visible = false"
      @onConfirm="commit"
    >
      <template v-slot:content>
        <el-form :model="addModel" ref="addRef" :rules="rules" size="default">
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="姓名" prop="nickname">
                <el-input
                  style="width: 300px"
                  placeholder="请输入用户名"
                  v-model="addModel.nickname"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="addModel.gender">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="电话" prop="phone">
                <el-input
                  style="width: 300px"
                  placeholder="请输入电话"
                  v-model="addModel.phone"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="邮箱" prop="email">
                <el-input
                  style="width: 300px"
                  placeholder="请输入邮箱"
                  v-model="addModel.email"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="用户" prop="username">
                <el-input
                  style="width: 300px"
                  placeholder="请输入登录名"
                  v-model="addModel.username"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="密码" prop="password">
                <el-input
                  type="password"
                  style="width: 300px"
                  placeholder="请输入登录密码"
                  v-model="addModel.password"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="角色" prop="roleId">
                <SelectChecked
                  :roleIds="roleIds"
                  ref="selectRef"
                  :options="options"
                  @selected="selected"
                ></SelectChecked>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </SysDialog>
    <el-table :data="tableList" style="width: 100%" border fit>
      <el-table-column
        label="真实姓名"
        prop="nickname"
        width="100px"
      ></el-table-column>
      <el-table-column label="性别" prop="gender" width="100px">
        <template #default="scope">
          <el-tag
            v-if="scope.row.gender == '1'"
            type="primary"
            closable
            size="default"
            effect="dark"
            >男</el-tag
          >
          <el-tag
            v-if="scope.row.gender == '2'"
            type="danger"
            closable
            size="default"
            effect="dark"
            >女</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="用户名"
        prop="username"
        width="200px"
      ></el-table-column>
      <el-table-column
        label="手机号"
        prop="phone"
        width="200px"
      ></el-table-column>
      <el-table-column
        label="邮箱"
        prop="email"
        width="200px"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        width="200px"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        prop="updateTime"
        width="200px"
      ></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <!-- 
            v-if="global.$hasPerm([`sys:user:edit`])"
          -->
          <el-button
            v-permission="[`sys:user:edit`]"
            type="primary"
            @click="handleEdit(scope.row)"
            icon="Edit"
            >编辑</el-button
          >
          <el-button
            v-permission="[`sys:user:delete`]"
            type="danger"
            @click="handleDelete(scope.row.id)"
            icon="Close"
            >删除</el-button
          >
          <el-button
            type="warning"
            @click="handlePassWord(scope.row)"
            icon="Close"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px; display: flex; justify-content: center"
      v-model:current-page="searchPaparm.currentPage"
      v-model:page-size="searchPaparm.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      layout="total, sizes, prev, pager, next"
      :total="searchPaparm.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="mt-4"
      background
    />
  </el-main>
</template>

<style scoped></style>
